package cn.hejiang.user.service.impl;

import cn.hejiang.basic.exception.BusinessException;
import cn.hejiang.basic.util.StrUtils;
import cn.hejiang.user.constant.UserConstants;
import cn.hejiang.user.domain.User;
import cn.hejiang.user.mapper.UserMapper;
import cn.hejiang.user.service.IVerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 非数据库业务
 */
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void smsCode(Map<String,String> param) {
        String phone = param.get("phone");
        String type = param.get("type");
        // 校验手机号不能为空
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)) {
            throw new BusinessException("参数不能为空,请重新输入");
        }

        String businessKey = "";
        // 注册逻辑
        if ("register".equals(type)) {
            // 查询t_user表，输入的手机号是否已经被注册
            User user = userMapper.loadByPhone(phone);
            if (user != null){
                throw new BusinessException("该手机号以注册，请直接登录或找回密码");
            }
            businessKey = UserConstants.BUSINESS_BINDER_PREFIX + phone;
        } else if ("binder".equals(type)) { // 绑定逻辑
            businessKey = UserConstants.BUSINESS_BINDER_PREFIX + phone;
        }
        if (StringUtils.hasLength(businessKey)) {
            sendCode(businessKey);
        }

    }

    // 发送验证码
    private void sendCode(String businessKey) {
        // 判断验证码是否有效，从redis中是否能拿到key
        Object codeTmp = redisTemplate.opsForValue().get(businessKey);
        String code = "";
        if (codeTmp != null) {
            // 拿到redis判断是否过来一分钟的重发时间
            String timeTmp = codeTmp.toString().split(":")[1];
            if (System.currentTimeMillis() - Long.valueOf(timeTmp) <= 1 * 60 * 1000) {
                // 如果未过重发时间，提示请勿重复获取验证码
                throw new BusinessException("请勿重复获取验证码！");
            } else {
                // 如果过了重发时间，使用上次的验证码
                code = codeTmp.toString().split(":")[0];
            }
        } else {
            // 如果拿不到，直接生成新的验证码
            code = StrUtils.getComplexRandomString(4);
        }

        // 储存redis,设置过期时间
        redisTemplate.opsForValue().set(businessKey,code + ":" + System.currentTimeMillis(), 3, TimeUnit.MINUTES);

        // 发送短信验证码通知
        System.out.println("您的验证码为：" + code + ";请在3分钟内使用！");
    }

}
